﻿using AskPro.Models.DataContext;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Mvc;

namespace AskPro.Models.Filters
{
    public class AuthorizeAsk : System.Web.Http.AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var Request = actionContext.Request;

            var authorizationHeader = Request.Headers.Authorization;
            string authParameter;

            if (authorizationHeader != null)
            {
                authParameter = authorizationHeader.Parameter;
                if (authParameter != null)
                {
                    //1. Decrypt parameters
                    string decodedParam = EncoderB64.Base64Decode(authParameter);
                    string[] authParams = decodedParam.Split('|'); //THE SPLITING SIGN!

                    string authorizationToken = authParams[0];
                    string deviceId = authParams[1];

                    //2. validate 
                    string tokenRecord = ConfigurationManager.AppSettings["AuthenticationCustomToken"];
                    if (authorizationToken == tokenRecord)
                    {
                        var dbContext = AskContext.Create();
                        DataContext.User dbUser;

                        if (dbContext.Users.Any(u => u.DeviceId == deviceId))
                        {
                            dbUser = dbContext.Users.Single(u => u.DeviceId == deviceId);
                        }
                        else //if there is none - create it!
                        {
                            dbUser = new DataContext.User();
                            dbUser.DeviceId = deviceId;
                            dbContext.Users.Add(dbUser);
                        }

                        var identity = new MyIdentity(true, dbUser.DeviceId);
                        HttpContext.Current.User = new MyPrincipal(identity, dbUser);

                        return true; //authorized!
                    }
                }
            }

            return false;
        }
    }
}